package com.warmlight.voicepacket.widget;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.io.IOException;

public class AudioPlayer {

    private MediaPlayer mediaPlayer;
    private static AudioPlayer mInstance;
    private String mAudioPath;
    private static long mFreshTime = 1000L;

    private static final int CHECK_POSITION = 0;
    public static int STATUS = Status.FREE.ordinal();

    public static final int AUDIO_FORMAT_ERROR = 255;//音频格式错误
    public static final int AUDIOPLAYER_INIT_ERROR = 254;//播放器初始化失败
    public static final int AUDIO_PATH_ERROR = 253;//播放地址为空

    public boolean isPlayer() {
        return mediaPlayer.isPlaying();
    }

    public enum Status{
        FREE,
        PLAYING,
        PAUSE,
        STOP,
        PREPARING
    }

    private AudioPlayer() {
        initPlayer();
    }

    public static AudioPlayer getInstance() {
        if(mInstance == null){
            synchronized (AudioPlayer.class){
                if(mInstance == null){
                    mInstance = new AudioPlayer();
                }
            }
        }
        return mInstance;
    }

    private void initPlayer(){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                if(mAudioActionListener != null){
                    mAudioActionListener.prepared(mediaPlayer.getDuration());
                }
                mediaPlayer.start();
                STATUS = Status.PLAYING.ordinal();
                if(mHandler != null){
                    mHandler.sendEmptyMessageDelayed(CHECK_POSITION, mFreshTime);
                }
                if(mAudioActionListener != null){
                    mAudioActionListener.play();
                }
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                complete();
                if(mAudioCompletedListener!=null){
                    mAudioCompletedListener.AudioCompleted();
                }
            }
        });

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if(mAudioExceptionListener != null){
                    mAudioExceptionListener.AudioPlayerError(what);
                }
                return false;
                //True if the method handled the error, false if it didn't.
                //Returning false, or not having an OnErrorListener at all, will
                //cause the OnCompletionListener to be called.
            }
        });
    }

    public void play(String path) {
        if(TextUtils.isEmpty(path)){
            if(mAudioExceptionListener != null){
                mAudioExceptionListener.AudioPlayerError(AUDIO_PATH_ERROR);
            }
            return;
        }

        //如果正在播放就暂停，此处根据需求而定暂停换播还是停了不管
//        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
//            if(path.equals(mAudioPath)){
//                pause();
//            }else{
//                stop();
//            }
//            return;
//        }
        //此处策略为，如果播放地址跟当前播放地址一样，则暂停，否则停止并换播
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            if(path.equals(mAudioPath)){
                pause();
                return;
            }else{
                stop();
            }
        }
        //当用户快速双击的时候，会导致无法暂停，因为未开始播放，报错了。回调了oncomplete
        if (STATUS == Status.PREPARING.ordinal()){
            STATUS = Status.FREE.ordinal();
            mediaPlayer.stop();
            mediaPlayer.reset();
            return;
        }
        // 如果播放器不为null且是暂停状态且url相同，则继续播放。
        if(mediaPlayer != null && path.equals(mAudioPath) && STATUS == Status.PAUSE.ordinal()){
            resume();
            return;
        }

        if (mediaPlayer == null) {
            initPlayer();
        }

        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(path);
        } catch (IOException e) {
            if(mAudioExceptionListener != null){
                mAudioExceptionListener.AudioPlayerError(AUDIOPLAYER_INIT_ERROR);
            }
            e.printStackTrace();
            return;
        }

        mAudioPath = path;
        STATUS = Status.PREPARING.ordinal();
        mediaPlayer.prepareAsync();
        //开始准备的回调
//        if(mAudioActionListener != null){
//            mAudioActionListener.preparing();
//        }

    }


    /**
     * AudioPlayer播放完毕的监听回调
     */
    private AudioCompletedListener mAudioCompletedListener;
    public interface AudioCompletedListener{
        void AudioCompleted();
    }
    public void setOnAudioCompletedListener(AudioCompletedListener listener){
        mAudioCompletedListener = listener;
    }


    public boolean seekTo(long time){
        if(mediaPlayer != null){
            //1，durition >= time；2，int range >> time
            mediaPlayer.seekTo((int)time);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 提供外界控制是否刷新UI接口，如果播放器未初始化或未在播放中，则无效。
     */
    public void loopUI(boolean refresh){
        if(mediaPlayer != null && mediaPlayer.isPlaying() && mHandler != null) {
            mHandler.removeMessages(CHECK_POSITION);
            if (refresh) {
                mHandler.sendEmptyMessageDelayed(CHECK_POSITION, mFreshTime);
            }
        }
    }

    /**
     * 继续播放
     * @return
     */
    public boolean resume(){
        if(mediaPlayer != null && !mediaPlayer.isPlaying()){
            mediaPlayer.start();
            STATUS = Status.PLAYING.ordinal();
            if(mHandler != null){
                mHandler.sendEmptyMessageDelayed(CHECK_POSITION, mFreshTime);
            }
        }else{
            return false;
        }
        if(mAudioActionListener != null){
            mAudioActionListener.resume();
        }
        return true;
    }

    /**
     * 停止播放并reset URL
     * @return
     */
    public boolean stop(){
        if(mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.reset();
            STATUS = Status.STOP.ordinal();
        }else{
            return false;
        }
        if(mAudioActionListener != null){
            mAudioActionListener.stop();
        }
        return true;
    }

    /**
     * 暂停播放
     * @return
     */
    public boolean pause(){
        if(mediaPlayer != null){
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                STATUS = Status.PAUSE.ordinal();
            }else{//未播放的时候按重置处理
                mediaPlayer.stop();
                mediaPlayer.reset();
                STATUS = Status.STOP.ordinal();
            }
        }else{
            return false;
        }
        if(mAudioActionListener != null){
            mAudioActionListener.pause();
        }
        return true;
    }

    /**
     * 播放完成并reset URL
     * @return
     */
    public boolean complete(){
        if(mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.reset();
            STATUS = Status.FREE.ordinal();
        }else{
            return false;
        }
        if(mAudioActionListener != null){
            mAudioActionListener.completed();
        }
        return true;
    }

    /**
     * 释放播放器资源
     * @return true 释放成功，false 已经释放完了。
     */
    public boolean release(){
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
            STATUS = Status.FREE.ordinal();
            return true;
        }
        return false;
    }

    /**
     * AudioPlayer行为的监听回调
     */
    private AudioActionListener mAudioActionListener;
    public interface AudioActionListener{
        void play();
        void resume();
        void pause();
        void stop();
        void completed();
        void position(long position);
        void prepared(long durition);
    }
    public void setOnAudioActionListener(long freshTime, AudioActionListener listener){
        mAudioActionListener = listener;
        mFreshTime = freshTime <= 20 ? 20 : freshTime;
    }

    /**
     * AudioPlayer异常的监听回调
     */
    private AudioExceptionListener mAudioExceptionListener;
    public interface AudioExceptionListener{
        void AudioPlayerError(int code);
    }
    public void setOnAudioExceptionListener(AudioExceptionListener listener){
        mAudioExceptionListener = listener;
    }

    /**
     * 获取当前播放器播放中状态的当前音频位置
     * @return 当前音频位置，如果未加载音频，则返回-1
     */
    public long getCurrent(){
        if(mediaPlayer!=null){
            return mediaPlayer.getCurrentPosition();
        }else{
            return -1;
        }
    }

    /**
     * 获取播放器当前加载音频的长度
     * @return 音频长度，如果未加载音频，则返回-1
     */
    public long getDuration(){
        if(mediaPlayer!=null){
            return mediaPlayer.getDuration();
        }else{
            return -1;
        }
    }

    /**
     * 获取播放器状态
     * @return status code
     */
    public int getStatus(){
        return STATUS;
    }

    //FIXME 1，static；2，WeakReference。https://blog.csdn.net/wuleihenbang/article/details/17126371
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CHECK_POSITION://正常循环刷新UI
                    if(mAudioActionListener != null && mediaPlayer != null && mediaPlayer.isPlaying()){
                        mAudioActionListener.position(mediaPlayer.getCurrentPosition());
                        //Log.e("TAG",mediaPlayer.getCurrentPosition()+"");
                        if(mHandler != null){
                            mHandler.sendEmptyMessageDelayed(CHECK_POSITION,mFreshTime);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };


}
